package com.song.hanlder;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.song.vo.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author Klys
 * @Date 2023/6/5 15:38
 * @Description
 * @Version 1.0
 */
@Component
@Slf4j
public class MyAccessDenyHanlder implements AccessDeniedHandler {

    @Autowired
    private ObjectMapper objectMapper;//可以进行序列化和反序列化

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {

        HttpResult res = new HttpResult(403, "您没有权限访问该资源", null);
        String responseJson = objectMapper.writeValueAsString(res);

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        PrintWriter printWriter = response.getWriter();
        printWriter.println(responseJson);
        printWriter.flush();
    }
}
